<template>
  <div class="register">
    <registerHead />
    <div class="registerBody">
      <div class="container">
        <div class="steps">
          <el-steps :active="preStep" align-center>
            <el-step title="注册方式"></el-step>
            <el-step title="注册信息"></el-step>
            <el-step title="注册成功"></el-step>
          </el-steps>
        </div>
        <div class="registerType">
          <div @click="checkType('phone')" :class="registerType==='phone'?'checked':''" class="type">手机号注册</div>
          <div :class="registerType==='phone'?'':'checked'" class="type">账号注册</div>
<!--          @click="checkType('account')"   -->
        </div>
        <div class="registerCon">
          <div class="registerConBox">
<!--            手机注册，发送验证码-->
            <div class="phoneRegister" v-show="preStep===1" v-if="registerType==='phone'">
              <el-input
                placeholder="请输入注册手机号"
                v-model="phoneNum"
                maxlength="11"
                @blur="phoneType"
                @focus="beforeToSetPwd='',phoneFalse=false"
                @input="phoneTypeTrue"
              ></el-input>
              <p class="verify"><span v-show="phoneFalse" v-text="phoneRegistered?phoneRegistered:phoneRule"></span></p>
              <el-button v-if="!isGetSms" class="getSms" @click="checkPhone" type="primary" :disabled="!isNum">点击发送短信验证码</el-button>
              <el-input v-if="isGetSms" placeholder="请输入内容" v-model="smsCode">
                <template slot="append">{{smsCodeTimeOut}}</template>
              </el-input>
              <p class="beforeToSetPwd">
                <span v-text="beforeToSetPwd"></span>
              </p>
              <div class="agreementBox">
                <div class="alertCheck" v-show="isAlert">
                  请阅读并勾选用户协议
                  <p class="arrows"></p>
                </div>
                <el-checkbox v-model="agreement" @change="checkAgreement">我已认真阅读并同意遵守</el-checkbox>
                <a @click="agreementDialog=true">《用户协议》</a>
                <el-dialog
                  :title="agreementData.title"
                  :visible.sync="agreementDialog"
                  :close-on-click-modal="false"
                  width="70%"
                  :lock-scroll="false">
                  <div style="max-height: 400px; overflow:auto" v-html="agreementData.content"></div>
                  <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="agreementDialog=false,agreement=true">确 定</el-button>
                  </span>
                </el-dialog>
              </div>
              <el-button @click="toSetPwd" class="nextStep" type="primary">下一步 </el-button>
            </div>
<!--            手机注册，设置密码-->
            <div class="phoneRegisterPwd" v-show="preStep===2">
              <h4>
                <i class="el-icon-arrow-left backIcon"></i>
                <i>手机号：</i>
                <span v-text="phoneNum?phoneNum:''"></span>
              </h4>
<!--              type="password"-->
              <el-input
                placeholder="请输入密码"
                show-password
                @focus="pwdRuleShow=true,isPwdRuleBlur=false"
                maxlength="16"
                @blur="verifyPwdRule"
                v-model="pwd"
              ></el-input>
              <p class="pwdRule">
                <span v-show="pwdRuleShow" v-text="pwdRuleText"></span>
                <span
                  v-show="isPwdRuleBlur"
                  v-text="pwd?'密码必须由数字、字母、特殊字符组合,请输入6-16位':'请输入密码'"
                  style="color: #f00"
                ></span>
              </p>
              <el-input
                type="password"
                placeholder="请再次输入密码"
                show-password
                @focus="repPwdRuleShow=false"
                @blur="verifyRepPwdRule"
                v-model="repPwd"
              ></el-input>
              <p class="repPwdRule">
                <span v-show="repPwdRuleShow" v-text="repPwdRuleText"></span>
              </p>
              <el-button @click="confirmRegister" class="confirmRegister">确认注册</el-button>
            </div>
<!--            手机注册（注册成功）-->
            <div class="phoneRegisterSuccess" v-show="preStep===3">
              <h4> <i class="el-icon-success" style="color: #63d08c;"></i>恭喜 <span>{{phoneNum}} 注册成功</span></h4>
              <p>绑定会员激活卡或在线升级你的会员权限，享受超多功能</p>
              <div class="userFunction">
                <div
                  class="function"
                  v-for="(item,index) in userFunction"
                  :key="index">
                  <div class="functionBg" :style="item.functionBgColor">VIP</div>
                  <h5 :style="item.functionBgColor">{{index+1}}.{{item.name}}</h5>
                  <p>{{item.p}}</p>
                </div>
              </div>
              <el-button class="activateBtn" type="primary">激活</el-button>
              <el-button @click="toExperience" class="noActivateBtn">稍后激活，即可体验</el-button>
            </div>
<!--            账号注册   -->
            <div class="accountRegister" v-if="registerType!=='phone'">
              <el-input
                placeholder="请输入注册账号名(3-20个字符，支持字母和数字)"
                v-model="account"
                @blur="accountType"
                @input="accountTypeTrue"
              ></el-input>
              <p class="verify"><span v-show="accountFalse">请输入正确的账号名</span></p>
              <el-checkbox v-model="agreement">我已认真阅读并同意遵守</el-checkbox>
              <a href="">《用户注册协议》</a>
              <el-button type="primary" class="nextStep">下一步 </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      :visible.sync="captchaDialog"
      :close-on-click-modal="false"
      append-to-body
      :center="true"
      :show-close="false"
      z-index="500"
      width="360px"
    >
      <Captcha
        v-model="captchaDialog"
        width="300px"
        height="240px"
        :max-dot="maxDot"
        :image-base64="imageBase64"
        :thumb-base64="thumbBase64"
        :error-prompt="errorPrompt"
        @close="handleCloseEvent"
        @refresh="handleRefreshEvent"
        @confirm="handleConfirmEvent"
      ></Captcha>
    </el-dialog>
  </div>
</template>

<script>
  import registerHead from '../common/registerHead.vue'
  import Captcha from './captcha/captcha.vue'
  import { userLogin } from '../../../api/user.js'
  import { getAgreement } from '../../../api/common.js'
  import { getCaptcha, checkCaptcha } from '../../../api/captcha.js'
  import { checkExist, getSmsCode, regSmsCode, confirmRegister } from '../../../api/register.js'
    export default {
        name: "register",
        data() {
            return {
                // 用户协议内容
                agreementData: '',
                // 步骤条
                preStep: 1,
                registerType: 'phone',
                agreement: false,
                agreementDialog: false,
                // 手机号注册
                isNum: false,
                phoneNum: '',
                phoneFalse: false,
                phoneRegistered: '',
                phoneRule: '手机号码不能为空',
                isGetSms: false,  // 是否已经获取验证码
                captchaDialog: false,
                // 请求的点选验证图片
                maxDot: 5,
                imageBase64: '',
                thumbBase64: '',
                captchaKey: '',
                errorPrompt: '',   // 点选验证返回的错误信息
                captchaToken: '',  // 点选验证返回的token
                // 短信验证码
                smsCode: '',
                smsCodeTimeOut: '发送验证码中',
                beforeToSetPwd: '',
                isAlert: false,
                // 设置密码
                pwdRuleText: '密码必须由数字、字母组合,请输入6-16位',
                pwdRuleShow: false,
                isPwdRuleBlur: false,
                repPwdRuleText: '',
                repPwdRuleShow: false,
                pwd: '',
                repPwd: '',
                // 注册成功
                userFunction: [
                    {name: 'E讲堂', p: '学练测评，补弱提优', functionBgColor: {color: '#9acf67'}},
                    {name: '生涯规划', p: '高中三年技巧规划，一步领先步步领先', functionBgColor: {color: '#59b6ff'}},
                    {name: '心灵成长', p: '心灵困惑，有我相伴', functionBgColor: {color: '#ff7ca3'}},
                    {name: 'E社区', p: '高中生的网上家园', functionBgColor: {color: '#4342ef'}},
                ],
                // 账号注册
                account: '',
                accountFalse: false,
            }
        },
        components: {
            registerHead,
            Captcha  // 点选验证码弹窗
        },
        created() {
            this.getAgreement(); // 获取用户协议内容
        },
        methods: {
            // 获取用户协议内容
            async getAgreement() {
              const res = await getAgreement({
                  id: 1
              });
                console.log(res);
                if(res.data.status) {
                    this.agreementData = res.data.data;
                }
            },
            // 选择注册类型
            checkType(type) {
                this.registerType = type;
                this.phoneFalse = false;
                this.accountFalse = false;
            },
            // 手机号验证
            phoneType() {
                let re = /^1[3456789]{1}\d{9}$/;
                let str = this.phoneNum;
                if(re.test(str)){
                    this.phoneFalse = false;
                }else {
                    // this.phoneFalse = true;
                    if(str.length>0) {
                        this.phoneRule = '手机号不符';
                        this.phoneFalse = true;
                    }else{
                        this.phoneRule = '手机号不能为空';
                        this.phoneFalse = true;
                    }
                }
            },
            // 手机号验证成功
            phoneTypeTrue() {
                let re = /^1[3456789]{1}\d{9}$/;
                let str = this.phoneNum;
                if(re.test(str)){
                    this.isNum = true;
                    this.phoneFalse = false;
                }else {
                    this.isNum = false;
                }
            },
            // 验证手机号是否已经存在
            async checkPhone() {
                this.beforeToSetPwd='';
                const res = await getCaptcha();
                if(res.status===200) {
                    this.captchaKey = res.data.captcha_key;
                    this.imageBase64 = res.data.image_base64;
                    this.thumbBase64 = res.data.thumb_base64;
                    if(this.imageBase64 && this.thumbBase64) {
                        this.captchaDialog = true;
                    }
                }
                // 先弹出点选验证码
                // 验证成功，验证手机号已经注册？
            },
            // 勾选协议
            checkAgreement() {
              if(this.agreement) {
                  this.isAlert = false;
              }
            },
            // 关闭(点选验证码)
            handleCloseEvent() {
                this.captchaDialog = false;
                this.errorPrompt = '';
            },
            // 刷新(点选验证码)
            async handleRefreshEvent() {
                this.errorPrompt = '';
                const res = await getCaptcha();
                if(res.status===200) {
                    this.captchaKey = res.data.captcha_key;
                    this.imageBase64 = res.data.image_base64;
                    this.thumbBase64 = res.data.thumb_base64;
                    if(this.imageBase64 && this.thumbBase64) {
                        this.captchaDialog = true;
                    }
                }
            },
            // 确认(点选验证码)
            async handleConfirmEvent(dots) {
                this.errorPrompt = '';
                let dotArr = [];
                dots.forEach(dot => {
                    dotArr.push(dot.x, dot.y)
                });
                const res = await checkCaptcha({
                    "dots": dotArr.join(','),
                    "key": this.captchaKey,
                });
                if (res.data.code===200){
                   // 验证通过，执行下面接口
                    this.captchaToken = res.data.data.captchaToken;
                    this.captchaDialog = false;
                    // 校验手机号是否注册
                    const isRegister = await checkExist({
                        "mobileAccount": this.phoneNum,
                        "captchaToken": this.captchaToken
                    });
                    if(isRegister.data.status) {
                        // 如果手机已经注册做出提示
                        this.phoneFalse = true;   // 错误手机提示
                        this.phoneRegistered = '该手机号已经注册';
                    }else{
                        // 手机未注册，执行后面接口
                        this.isGetSms = true;  // 手机未注册，获取验证码
                        const smsCode = await getSmsCode({
                            "mobile": this.phoneNum,
                            "token": this.captchaToken
                        });
                        if(smsCode.data.status) {
                            this.captchaToken = smsCode.data.data.checkToken;
                            // 获取验证码，倒计时
                            let i = 120;
                            let timer = setInterval(() => {
                                this.smsCodeTimeOut = i + 's后重试';
                                i--;
                                if (i < 0) {
                                    this.isGetSms = false;
                                    clearInterval(timer);
                                    this.smsCodeTimeOut = '发送验证码中';
                                }
                            }, 1000);
                        }
                    }
                }else{
                    //如果验证错误或未点选则弹出对话框或错误提示
                    this.errorPrompt = res.data.msg;
                    //并刷新下验证码让用户重新选择
                }
            },
            // 获取验证码，下一步，设置密码
            async toSetPwd() {
                if(this.agreement) {
                    // 如果勾选了协议
                    const res = await regSmsCode({
                        "mobile": this.phoneNum,
                        "captchaToken": this.captchaToken,
                        "smsCode": this.smsCode
                    });
                    if(res.data.status) {
                        this.captchaToken = res.data.data.captchaToken;
                        // 跳转设置密码页面
                        this.preStep = 2;
                    }else{
                        if(this.phoneNum) {
                            // 如果填了手机号，没有获取验证码
                            this.beforeToSetPwd = res.data.msg;
                        }else{
                            // 没有填写手机号
                            // this.phoneRule = res.data.msg;
                            this.phoneFalse = true;
                        }
                    }
                }else{
                    // 如果没有勾选协议，提示勾选
                    this.isAlert = true;
                }
            },
            // 密码规则验证
            verifyPwdRule() {
                let str = this.pwd;
                let re = /(?=.*\d)(?=.*[a-zA-Z]).{6,16}/;
                if (re.test(str)) {
                    console.log('正确');
                    this.pwdRuleShow=false;
                }else{
                    console.log('错误');
                    this.pwdRuleShow = false;
                    this.isPwdRuleBlur = true;
                }
            },
            // 重复密码验证
            verifyRepPwdRule() {
                if(this.repPwd) {
                    if(this.repPwd!==this.pwd) {
                        this.repPwdRuleText = '两次密码不一致';
                        this.repPwdRuleShow = true;
                    }else{
                        this.repPwdRuleText = '';
                        this.repPwdRuleShow = false;
                    }
                }else{
                    this.repPwdRuleText = '请再次输入密码';
                    this.repPwdRuleShow = true;
                }
            },
            // 确认注册
            async confirmRegister() {
              let data = {
                  "mobile": this.phoneNum,
                  "captchaToken": this.captchaToken,
                  "password": this.pwd,
                  "checkPassword": this.repPwd
              };
              // 密码一致 且 规则通过
              if(this.pwd===this.repPwd && !this.repPwdRuleShow) {
                  const res = await confirmRegister(data);
                  if(res.data.status) {
                      // 跳转成功页
                      console.log(res.data);
                      this.preStep = 3;
                      // base64加密
                      let Base64 = require('js-base64').Base64;
                      this.pwd = Base64.encode(this.pwd);
                      const login = await userLogin({
                          "userName": this.phoneNum,
                          "password": this.pwd,
                          "client": "pc"
                      });
                      if(login.data.status) {
                          sessionStorage.setItem('token',JSON.stringify(login.data.data.token));
                          sessionStorage.setItem('userId',JSON.stringify(login.data.data.userId));
                      }
                  }
              }
            },
            // 去体验
            toExperience() {
              this.$router.push('plan');
            },
            // 账号验证
            accountType() {

            },
            accountTypeTrue() {

            }
        }
    }
</script>

<style scoped lang="scss">
  @import '../../../styles/common.scss';
  .register{
    .registerBody{
      .steps{
        padding: 20px 90px;
        margin: 50px 0;
      }
    }
    .registerType{
      margin: auto;
      width: 40%;
      display: flex;
      justify-content: space-between;
      .type{
        padding: 20px 4px 10px;
        font-size: 1rem;
        border-bottom: 1px solid #fff;
        cursor: pointer;
      }
      .type.checked{
        border-bottom: 1px solid #2e86ff;
        color: #2e86ff;
      }
    }
    .registerCon{
      .registerConBox{
        margin: auto;
        width: 40%;
        padding: 10px 0;
        .el-input{
          margin: 14px 0 4px;
        }
        .verify,.beforeToSetPwd{
          color: #f00;
          font-size: 0.6rem;
          height: 16px;
        }
        .getSms{
          width: 100%;
          height: 48px;
          color: #666;
          background-color: #f4f4f4;
          border-color: #e7ebf0;
          margin-top: 20px;
          margin-bottom: 10px;
        }
        .nextStep{
          width: 100%;
          margin: 20px 0;
          font-size: 1rem;
          background: #2e86ff;
          border-color: #2e86ff;
        }
        .el-checkbox{
          color: #000;
          margin-top: 30px;
        }
        .agreementBox{
          position: relative;
          .alertCheck{
            position: absolute;
            top: -14px;
            left: -10px;
            background-color: rgba(0,0,0,0.8);
            color: #fff;
            padding: 6px 12px;
            border-radius: 5px;
            .arrows{
              position: absolute;
              left: 8px;
              bottom: -12px;
              width: 0;
              height: 0;
              border-left: 8px solid transparent;
              border-right: 8px solid transparent;
              border-top: 12px solid rgba(0,0,0,0.8);
            }
          }
        }
        a{
          color: #2f8efa;
          cursor: pointer;
        }
        // 密码盒子
        .phoneRegisterPwd{
          h4{
            i{
              font-style: normal;
              color: #666;
            }
            .backIcon{
              color: #000;
              cursor: pointer;
              margin-right: 6px;
            }
            span{
              font-size: 0.7rem;
              color: #333;
            }
          }
          .pwdRule{
            height: 10px;
            padding-left: 4px;
            span{
              font-size: 0.6rem;
              color: #aaa;
            }
          }
          .repPwdRule{
            height: 10px;
            padding-left: 4px;
            span{
              font-size: 0.6rem;
              color: #f00;
            }
          }
          .confirmRegister{
            background-color: #2e86ff;
            color: #fff;
            width: 100%;
            margin: 20px 0;
            font-size: 1rem;
            border-color: #2e86ff;
          }
        }
        // 成功盒子
        .phoneRegisterSuccess{
          h4{
            margin: 20px 0 10px;
            text-align: center;
            font-size: 1.2rem;
            i{
              font-size: 1.2rem;
              padding-right: 6px;
            }
            span{
              font-size: 1.2rem;
            }
          }
          p{
            text-align: center;
            color: #666;
            margin-bottom: 40px;
          }
          .activateBtn{
            width: 100%;
            margin: 20px 0;
            background-color: #2e86ff;
          }
          .noActivateBtn{
            width: 100%;
            margin-left: 0;
            background-color: #f4f4f4;
          }
          .userFunction{
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            .function:hover{
              box-shadow: 0 0 3px 3px #f0f0f0;
            }
            .function{
              cursor: pointer;
              width: 48%;
              min-height: 80px;
              margin: 10px 0;
              box-shadow: 0 0 3px 3px #f6f6f6;
              position: relative;
              .functionBg{
                position: absolute;
                bottom: -16PX;
                right: 4px;
                font-size: 3.5rem;
                font-weight: bolder;
                color: #f00;
                opacity: 0.1;
              }
              h5{
                margin: 10px 0 4px 10px;
                /*font-weight: normal;*/
                font-size: 0.8rem;
              }
              p{
                margin: 0 10px;
                text-align: left;
                font-size: 0.8rem;
              }
            }
          }
        }
      }
    }
  }
</style>